import React, {useCallback, useState} from 'react'
import './index.scss'
import {Picker, View, Input, Button, Text} from "@tarojs/components";
import Taro from "@tarojs/taro";
import {reverseGeocoder} from "@/utils/common/lbs";



interface Region {
  province: string;
  city: string;
  district: string;
}

type ValueType = {
  detail: string;
  region: string;
}

interface Iprops {
  onChange: (value: ValueType) => void

}
function AddressSelect(props: Iprops) {
  const [region, setRegion] = useState<Region>({
    province: '',
    city: '',
    district: '',
  });
  const [detailedAddress, setDetailedAddress] = useState('');

  const handleRegionChange = useCallback((e) => {
    const { value } = e.detail;
    const reg = {
      province: value[0],
      city: value[1],
      district: value[2],
    }
    setRegion(reg);
    props?.onChange({region: reg['province'] + reg['city'] + reg['district'], detail: detailedAddress})
  }, []);

  const handleDetailedAddressInput = useCallback((e) => {
    setDetailedAddress(e.target.value);
    props?.onChange({region: region['province'] + region['city'] + region['district'], detail: e.target.value})
  }, [region]);

  const getLocation = useCallback(async () => {
    Taro.showLoading()
    try {

      const {provinceName: province, cityName: city, countyName: district, detailInfo} =  await Taro.chooseAddress();
      //
      // const {latitude, longitude} = await Taro.getLocation({ type: 'gcj02' });
      // const  locationInfo  = await reverseGeocoder({latitude, longitude})
      // if (locationInfo.status !== 0) {
      //   return ;
      // }
      // const {result} = locationInfo
      // const {province, city, district} = result.address_component
      setRegion({
        province,city,district
      })
      const prefix = province + city + district
      setDetailedAddress(detailInfo)
      props?.onChange({region: prefix, detail: detailInfo})
    } catch (error) {
      const msg = '获取位置信息失败:'
      console.error(msg, error);
      Taro.showToast({
        title: msg,
        icon: 'none'
      })
    } finally {
      Taro.hideLoading()
    }
  }, []);

  return (
    <View>
      <Picker mode='region' onChange={handleRegionChange} className='xxm-picker'>
        <View >
          {region.district ? `${region.province} / ${region.city} / ${region.district}`  : (
            <View className='placeholder'>
              省/市/区 点击选择
            </View>
          )}
        </View>
      </Picker>
      <View style={{margin: '12px 0', display: 'flex'}}>
        <Text>详细地址</Text>
        <Input
          style={{marginLeft: 24, flex: '1'}}
          placeholder='请输入详细地址'
          value={detailedAddress}
          onInput={handleDetailedAddressInput}
        />
      </View>
      <Button onClick={getLocation} size='mini'>获取位置</Button>
    </View>
  )
}

export default AddressSelect
